import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: LeetCode
 * @description: LeetCode : 数组的交集
 * @author: WXY
 * @create: 2023-01-02 14:29
 * @Version 1.0
 **/
public class num350_intersect {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
        }
        int[] ans = new int[nums1.length];
        int index = 0;
        for (int num : nums2) {
            if (map.containsKey(num) && map.get(num) > 0) {
                ans[index++] = num;
                map.put(num, map.get(num) - 1);
            }
        }
        return Arrays.copyOfRange(ans, 0, index);
    }
}
